package com.pmenergy.util;
import java.util.List;

import javax.el.ELContext;
import javax.el.ValueExpression;
import javax.faces.component.UIComponent;
import javax.faces.component.visit.VisitResult;

import org.apache.commons.lang3.ArrayUtils;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.context.RequestContext;
import org.primefaces.extensions.util.visitcallback.VisitTaskExecutor;

public class UpdateDataTableExecutor implements VisitTaskExecutor {  
  
    //private static final String INDEX_ATTR = "nombre";  
  
    private ELContext elContext;  
    private RequestContext requestContext;  
    private String[] ids;  
    private List<Object> objetos;
    
  
    public UpdateDataTableExecutor(ELContext elContext, RequestContext requestContext, String[] ids, List<Object> objetos) {  
        this.elContext = elContext;  
        this.requestContext = requestContext;  
        this.ids = ids; 
        this.objetos=objetos;
        
    }  

    public VisitResult execute(UIComponent component) {  
    	DataTable dataTable = (DataTable) component;
    	String id = dataTable.getId(); 
    	
    	
    	ValueExpression ve = dataTable.getValueExpression("value");  
    	
    	ve.setValue(elContext, objetos);
        
        requestContext.update(dataTable.getClientId());
    	
    	ArrayUtils.removeElement(ids, id);
    	
    	
    	return (ids.length != 0) ? VisitResult.REJECT : VisitResult.COMPLETE;
    }

	@Override
	public boolean shouldExecute(UIComponent component) {
		// TODO Auto-generated method stub
		if (component instanceof DataTable)  {
			if (ArrayUtils.contains(ids, component.getId())){				
				return true;
	        }  
        }  
  
        return false; 
	}  
  
    }
